import { Component, OnInit } from '@angular/core';
import { ZoneService, ZonePersonnel, Zone } from 'app/modules/zone/services/zone.service';
import { PersonnelService, PersonnelInfo } from 'app/modules/personnel/services/personnel.service';
import { BehaviorSubject, combineLatest } from 'rxjs';
import { map, startWith, skip } from 'rxjs/operators';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, FormControl } from '@angular/forms';
import { MySelection } from 'app/modules/base/selection';

@Component({
	selector: 'm-receiver',
	templateUrl: './receiver.component.html',
	styleUrls: ['./receiver.component.scss'],
	providers: [
		{
			multi: true,
			provide: NG_VALUE_ACCESSOR,
			useExisting: ReceiverComponent,
		},
	],
})
export class ReceiverComponent implements OnInit, ControlValueAccessor {
	constructor(private zoneService: ZoneService, private personnelService: PersonnelService) {}
	zoneSelectControl = new FormControl([]);
	personnelAPI$ = this.zoneSelectControl.valueChanges.pipe(
		startWith([]),
		map((zones: Zone[]) => {
			if (zones.length && zones[0].id) {
				return this.zoneService.resource(zones[0].area_id, 'user');
				// return this.zoneService.resource(zones[0].id, 'user');
			}
			return this.personnelService;
		}),
	);
	zoneSelection = new MySelection<Zone>('id');
	personnelSelection = new MySelection<ZonePersonnel>('id');

	value$ = combineLatest(
		this.zoneSelection.change.pipe(startWith([])),
		this.personnelSelection.change.pipe(startWith([])),
	).pipe(
		map(() => {
			const zones = this.zoneSelection.selected;
			const users = this.personnelSelection.selected;
			return { zones, users };
		}),
	);

	ngOnInit() {}

	writeValue(obj: any): void {}
	registerOnChange(fn: any): void {
		this.value$.subscribe(fn);
	}
	registerOnTouched(fn: any): void {
		this.value$.pipe(skip(1)).subscribe(fn);
	}
}
